package projectAnalysis.advancedTechAnalyzer;

import org.apache.maven.model.Dependency;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

public class MavenDependencyAnalyzer {
    // 解析pom.xml获取直接依赖（添加进度输出）
    public List<Dependency> parseDirectDependencies(File projectDir) throws IOException, XmlPullParserException {
        File pomFile = new File(projectDir, "pom.xml");
        if (!pomFile.exists()) {
            System.out.println("未找到pom.xml，跳过Maven直接依赖解析");
            return java.util.Collections.emptyList();
        }

        System.out.println("开始解析Maven直接依赖...");
        MavenXpp3Reader reader = new MavenXpp3Reader();
        Model model = reader.read(new FileReader(pomFile));
        List<Dependency> dependencies = model.getDependencies();
        System.out.println("完成Maven直接依赖解析，共找到 " + dependencies.size() + " 个直接依赖");
        return dependencies;
    }

    // 解析传递依赖（添加实时进度）
    public void parseTransitiveDependencies(File projectDir, String mavenBinPath) {
        try {
            String mvnCommand = mavenBinPath + File.separator +
                    (System.getProperty("os.name").contains("Windows") ? "mvn.cmd" : "mvn");

            System.out.println("开始解析Maven传递依赖... 命令：" + mvnCommand + " dependency:tree");
            Process process = new ProcessBuilder(
                    mvnCommand, "dependency:tree", "-DoutputFile=dependency-tree.txt"
            ).directory(projectDir).start();

            // 实时输出Maven命令的日志（避免卡住的错觉）
            new Thread(() -> {
                try (java.io.BufferedReader reader = new java.io.BufferedReader(
                        new java.io.InputStreamReader(process.getInputStream()))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        System.out.println("[Maven日志] " + line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();

            int exitCode = process.waitFor();
            if (exitCode == 0) {
                System.out.println("Maven传递依赖解析完成，结果已输出到：" + projectDir.getAbsolutePath() + "/dependency-tree.txt");
            } else {
                System.out.println("Maven传递依赖解析失败，退出码：" + exitCode);
            }
        } catch (Exception e) {
            System.out.println("解析传递依赖出错：" + e.getMessage());
        }
    }
}